<?php 


//加密和解密方法
function tcodes($string, $isEncrypt = true, $key)
{
	$key  	= strtolower(md5($key));

    $dynKey = $isEncrypt ? hash('sha1', microtime(true)) : substr($string, 0, 40);
    $dynKey1 = substr($dynKey, 0, 20);
	$dynKey2 = substr($dynKey, 20);

	$fixKey = hash('sha1', $key);
    $fixKey1 = substr($fixKey, 0, 20);
    $fixKey2 = substr($fixKey, 20);

    $newkey = hash('sha1', $dynKey1 . $fixKey1 . $dynKey2 . $fixKey2);

    if($isEncrypt){
        $newstring = $fixKey1 . $string . $dynKey2;
    }else{
    	$newstring = base64_decode(substr($string, 40));
    }

    $re = '';
    $len = strlen($newstring);
    for ($i = 0; $i < $len; $i++)
    {
    	$j = $i % 40;
    	$re .= chr(ord($newstring{$i}) ^ ord($newkey{$j}));
    }

    return $isEncrypt ? $dynKey . str_replace('=', '_', base64_encode($re)) : substr($re, 20, -20);
}

/**
* 下载本地的文件
* @parm url 即本地的文件路径
*/
function localDownFile($url){
	if(file_exists($url)){
		$name 	= (strrpos($url, '/') == true )? substr($url , (strrpos($url, '/')+1) ): $url;
		$file 	= fopen($url, "r");  //打开文件url		
		header("Content-Type: application/octet-stream"); //指定mime类型为八进制文件流		
		header("Accept-Ranges: bytes");		
		header("Accept-Length: ".filesize($url));		
		header("Content-Disposition: attachment; filename=$name");  //$name是文件的名字，一般在$url的最后		
		echo fread($file,filesize($url));		
		fclose($file);
	}else{
		return false;
	}	
}

//str 查找的字符串
//find 需要查询到的图片
//n 第n次
function str_n_pos($str,$find,$n){
	for ($i=1;$i<=$n;$i++){
		$pos = strpos($str,$find);
		$str = substr($str,$pos+1);
		$pos_val=$pos+$pos_val+1;
	}
	return $pos_val-1;
}

/** 获取当前时间戳，精确到毫秒 */
function microtime_float()
{
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}

/** 格式化时间戳，精确到毫秒，x代表毫秒 */
function microtime_format($tag, $time)
{
   list($usec, $sec) = explode(".", $time);
   $date = date($tag,$usec);
   return str_replace('x', $sec, $date);
}



/**
 * 排序方法
 * $list 二维数据
 * $field 排序的字段
 * $sortby 怕徐规则
 * return 排好序的数组
 */
function list_sort_by($list, $field, $sortby = 'asc')
{
    if (is_array($list))
    {
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
        {
            $refer[$i] = &$data[$field];
        }
        switch ($sortby)
        {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc': // 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val)
        {
            $resultSet[] = &$list[$key];
        }
        return $resultSet;
    }
    return false;
}



/**
 * 生成word文档
 */
function word($data,$fileName=''){
	if(empty($data)) return '';
	$data='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">'.$data.'</html>';
	if(empty($fileName)) $fileName=date('YmdHis').'.doc';
	$fp=fopen($fileName,'wb');
	fwrite($fp,$data);
	fclose($fp);
}

function downloadWord($content, $file=''){
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=$file");
    $ext = substr(end(explode('.', $file)), 0, 3);
    switch($ext){
        case 'doc' : 
            $html = '<html xmlns:v="urn:schemas-microsoft-com:vml"xmlns:o="urn:schemas-microsoft-com:office:office"
                 xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"xmlns="http://www.w3.org/TR/REC-html40">';
            $html .= '<head></head>';
            break;
        case 'xls':
            $html = '<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
            $html .= '<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name></x:Name><x:WorksheetOptions><x:Selected/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>';
    }
    echo $html . '<body>'.$content .'</body></html>';
     
}

//下载存在的文件 组装的文件可能需要另外做
function downloadFile($filepath){
	$file=fopen($filepath,"r");
	header('Content-Encoding: utf-8');
	header("Content-Type: application/octet-stream");
	header("Accept-Ranges: bytes");
	header("Accept-Length: ".filesize($filepath));
	header('Content-Transfer-Encoding: binary' );
	header('Content-Disposition: attachment; filename='.basename($filepath));
	echo fread($file,filesize($filepath));
	fclose($file);
}


/**
 * 去掉html标签 指定
 */
function strip_selected_tags($text, $tags = array())
{
	$args = func_get_args();
	$text = array_shift($args);
	$tags = func_num_args() > 2 ? array_diff($args,array($text))  : (array)$tags;
	foreach ($tags as $tag){
	   	if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){
	       $text = str_replace($found[0],$found[1],$text);
	 	}
	}
	return $text;
}


/**
 * 发送HTTP请求
 *
 * @param string $url 请求地址
 * @param string $method 请求方式 GET/POST
 * @param string $refererUrl 请求来源地址
 * @param array $data 发送数据
 * @param string $contentType 
 * @param string $timeout
 * @param string $proxy
 * @return boolean
 */
function send_request($url, $data, $refererUrl = '', $method = 'GET', $contentType = 'application/json', $timeout = 30, $proxy = false) {
	$ch = null;
	if('POST' === strtoupper($method)) {
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER,0 );
		curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		if ($refererUrl) {
			curl_setopt($ch, CURLOPT_REFERER, $refererUrl);
		}
		if($contentType) {
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:'.$contentType));
		}
		if(is_string($data)){
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		} else {
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		}
	} else if('GET' === strtoupper($method)) {
		if(is_string($data)) {
			$real_url = $url. (strpos($url, '?') === false ? '?' : ''). $data;
		} else {
			$real_url = $url. (strpos($url, '?') === false ? '?' : ''). http_build_query($data);
		}

		$ch = curl_init($real_url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:'.$contentType));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		if ($refererUrl) {
			curl_setopt($ch, CURLOPT_REFERER, $refererUrl);
		}
	} else {
		$args = func_get_args();
		return false;
	}

	if($proxy) {
		curl_setopt($ch, CURLOPT_PROXY, $proxy);
	}
	$ret = curl_exec($ch);
	$info = curl_getinfo($ch);
	$contents = array(
			'httpInfo' => array(
					'send' => $data,
					'url' => $url,
					'ret' => $ret,
					'http' => $info,
			)
	);

	curl_close($ch);
	return $ret;
}

//随机字符串
function createRand($len = null){
	if($len == null){
		$len = 18;
	}
	$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789';
	$randstr = '';
    for ( $i = 0; $i < $len; $i++ ) 
    {
        // 这里提供两种字符获取方式
        // 第一种是使用 substr 截取$chars中的任意一位字符；
        // 第二种是取字符数组 $chars 的任意元素
        // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        $randstr .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }

    return $randstr;
}


/**
* 获取当前页面完整URL地址
*/
// function get_url() {
// 	return $_SERVER['PHP_SELF'];
// }
/**
* 获取当前页面完整URL地址
*/
function get_url() {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}


/*
* 判断访问时ios还是android
*/

function getUserAgent(){
	$userAgent = $_SERVER['HTTP_USER_AGENT'];
	if(preg_match("/(iPod|iPad|iPhone)/", $userAgent)){
		return 'ios';
	}elseif(preg_match("/android/i", $userAgent)){
		return 'android';
	}elseif(preg_match("/WP/", $userAgent)){
		return 'wp';
	}else{
		return 'other';
	}
}